package com.sjf.weibos;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.util.Log;


public class NetTool {
    public static final String BOUNDARY = "7cd4a6d158c";
    public static final String MP_BOUNDARY = "--" + BOUNDARY;
    public static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--";
    public static HttpClient getSSLHttpClient(Context context) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 10000);

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            HttpConnectionParams.setConnectionTimeout(params, 40000);
            HttpConnectionParams.setSoTimeout(params, 40000);
            HttpClient client = new DefaultHttpClient(ccm, params);
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (!wifiManager.isWifiEnabled()) {
                Uri uri = Uri.parse("content://telephony/carriers/preferapn");
                Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
                if (mCursor != null && mCursor.moveToFirst()) {
                    String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                    if (proxyStr != null && proxyStr.trim().length() > 0) {
                        HttpHost proxy = new HttpHost(proxyStr, 80);
                        client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                    }
                    mCursor.close();
                }
            }
            return client;
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }
	
	public static InputStream POST(Context context,String url,String params)throws Exception{
		HashMap<String, String> map = new HashMap<String, String>();
		HttpClient client;
			client = getSSLHttpClient(context);
		Log.e("params", params);
		HttpPost request = new HttpPost(url);
		
        byte[] data = null;
        ByteArrayOutputStream 
        bos = new ByteArrayOutputStream(1024 * 50);
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        StringBuffer pa=new StringBuffer();
        System.out.println(params);
        Map<String,String> m=OAuth.getMap(params);
        for(Iterator<String> it=m.keySet().iterator();it.hasNext();){
        	String key=it.next();
        	pa.append(key);
        	pa.append("=");
        	pa.append(URLEncoder.encode(m.get(key)));
        	pa.append("&"); 
        }
        pa=pa.deleteCharAt(pa.length()-1);
        Log.e("postParam", pa.toString());
        data = pa.toString().getBytes("UTF-8");
        bos.write(data);
        data = bos.toByteArray();
        bos.close();
        ByteArrayEntity formEntity = new ByteArrayEntity(data);
        request.setEntity(formEntity);
       
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			Log.e("SC_OK", "OK");
			return response.getEntity().getContent();
		}
		Log.e("CODE", response.getStatusLine().getStatusCode()+"");
		return null;
	}
	
	public static InputStream POST(String url,String params)throws Exception{
		HashMap<String, String> map = new HashMap<String, String>();
		String[] pp=params.split("&");
		for (int i = 0; i < pp.length; i++) {
			String kv=pp[i];
			String[] keyValue=kv.split("=");
			if(keyValue.length>1){
				map.put(keyValue[0], keyValue[1]);
			}else{
				map.put(keyValue[0],"");
			}
		}
		HttpPost request = new HttpPost(url);
		List<NameValuePair> p = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			p.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		HttpEntity entity = new UrlEncodedFormEntity(p, "UTF-8");
		request.setEntity(entity);
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 40000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		int timeoutSocket = 40000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient client = new DefaultHttpClient(httpParameters);
		HttpResponse response = client.execute(request);
		Log.e("CODE",response.getStatusLine().getStatusCode()+"");
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return response.getEntity().getContent();
		}
		return null;
	}
    public static String openUrl(Context context, String url,Map<String ,String> param, File file, String access) throws IllegalStateException, Exception {
        String result = "";
        try {
            HttpClient client = getSSLHttpClient(context);
            HttpUriRequest request = null;
            ByteArrayOutputStream bos = null;
            StringBuffer pa=new StringBuffer();
            for(Iterator<String> it=param.keySet().iterator();it.hasNext();){
            	String key=it.next();
            	pa.append(key);
            	pa.append("=");
            	pa.append(URLEncoder.encode(param.get(key)));
            	pa.append("&");
            }
            pa=pa.deleteCharAt(pa.length()-1);
            Log.e("POST", url + "?" + pa.toString());
            HttpPost post = new HttpPost(url);
            byte[] data = null;
            bos = new ByteArrayOutputStream(1024 * 50);

          if (file!=null&&file.exists()) {
              paramToUpload(bos, param);
              post.setHeader("Content-Type", "multipart/form-data" + "; boundary=" + BOUNDARY);
              Bitmap bf = BitmapFactory.decodeFile(file.getAbsolutePath());
              imageContentToUpload(bos, bf);
          } else {
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            Log.e("postParam", pa.toString());
            data = pa.toString().getBytes("UTF-8");
            bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
            request = post;
            request.setHeader("Authorization", "OAuth2 "+access);
            HttpResponse response = client.execute(request);
            StatusLine status = response.getStatusLine();
            int statusCode = status.getStatusCode();
            System.out.println(new String(read(response.getEntity().getContent()),"UTF-8"));
            // parse content stream from response
            Log.e("statusCode", statusCode+"");
            return result;
        } catch (IOException e) {
        }
		return result;
    }
    
	public static byte[] read(InputStream inputStream) throws Exception {
		ByteArrayOutputStream arrayBuffer = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(b)) != -1) {
			arrayBuffer.write(b, 0, len);
		}
		inputStream.close();
		arrayBuffer.close();
		return arrayBuffer.toByteArray();
	}
    private static void paramToUpload(OutputStream baos, Map<String ,String> params){
        String key = "";
        for (Iterator<String> it = params.keySet().iterator();it.hasNext();) {
            key = it.next();
            StringBuilder temp = new StringBuilder(10);
            temp.setLength(0);
            temp.append(MP_BOUNDARY).append("\r\n");
            temp.append("content-disposition: form-data; name=\"").append(key).append("\"\r\n\r\n");
            temp.append(params.get(key)).append("\r\n");
            byte[] res = temp.toString().getBytes();
            try {
                baos.write(res);
            } catch (IOException e) {
            }
        }
    }
    
    private static void imageContentToUpload(OutputStream out, Bitmap imgpath){
        StringBuilder temp = new StringBuilder();
        temp.append(MP_BOUNDARY).append("\r\n");
        temp.append("Content-Disposition: form-data; name=\"pic\"; filename=\"")
                .append("news_image").append("\"\r\n");
//        String filetype = "application/octet-stream";
        String filetype = "image/png";
        temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
        byte[] res = temp.toString().getBytes();
        BufferedInputStream bis = null;
        try {
            out.write(res);
            imgpath.compress(CompressFormat.PNG, 75, out);
            out.write(("\r\n"+ END_MP_BOUNDARY).getBytes());
            out.write(("\r\n").getBytes());
        } catch (IOException e) {
        } finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
